﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;

namespace Enlightener.Engine.Utils
{
    public static class Extensions
    {
        public static MethodDefinition FindMethod(this AssemblyDefinition asmDef, Predicate<MethodDefinition> pred)
        {
            return (from typeDef in asmDef.MainModule.Types from mDef in typeDef.Methods where pred(mDef) select mDef).FirstOrDefault();
        }

        public static IEnumerable<MethodDefinition> FindMethods(this AssemblyDefinition asmDef, Predicate<MethodDefinition> pred)
        {
            return from typeDef in asmDef.MainModule.Types from mDef in typeDef.Methods where pred(mDef) select mDef;
        }

        public static List<Instruction> GetInstructionBlock(this Collection<Instruction> instructions, int startIndex, int count)
        {
            var outList = new List<Instruction>();

            for (var i = startIndex; i < startIndex + count; i++)
                outList.Add(instructions[i]);

            return outList;
        }

        public static T GetOperandAt<T>(this Collection<Instruction> instructions, OpCode opCode, int index)
        {
            for (int i = 0, x = 0; i < instructions.Count; i++)
                if (instructions[i].OpCode == opCode)
                    if (x++ == index)
                        return (T)instructions[i].Operand;

            return default(T);
        }
    }
}
